package com.shop.cereshop.app.service.product.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.alioss.service.FileUploadService;
import com.shop.cereshop.app.alioss.service.UploadService;
import com.shop.cereshop.app.dao.product.CereShopProductDAO;
import com.shop.cereshop.app.page.canvas.CanvasProduct;
import com.shop.cereshop.app.page.index.Product;
import com.shop.cereshop.app.page.product.*;
import com.shop.cereshop.app.param.canvas.CanvasAppProductParam;
import com.shop.cereshop.app.param.index.SearchParam;
import com.shop.cereshop.app.param.product.ProductParam;
import com.shop.cereshop.app.param.product.ShareParam;
import com.shop.cereshop.app.param.product.SkuParam;
import com.shop.cereshop.app.redis.service.api.StringRedisService;
import com.shop.cereshop.app.service.activity.CereBuyerCouponService;
import com.shop.cereshop.app.service.activity.CerePlatformActivityService;
import com.shop.cereshop.app.service.buyer.CereBuyerCommentLikeService;
import com.shop.cereshop.app.service.buyer.CereBuyerReceiveService;
import com.shop.cereshop.app.service.buyer.CereBuyerSeckillVisitService;
import com.shop.cereshop.app.service.buyer.CereBuyerShopCouponService;
import com.shop.cereshop.app.service.collect.CereBuyerCollectService;
import com.shop.cereshop.app.service.collect.CereBuyerFootprintService;
import com.shop.cereshop.app.service.coupon.CereShopCouponService;
import com.shop.cereshop.app.service.discount.CereShopDiscountService;
import com.shop.cereshop.app.service.distributor.CereShopDistributorService;
import com.shop.cereshop.app.service.groupwork.CereShopGroupWorkService;
import com.shop.cereshop.app.service.product.CereCommentWordService;
import com.shop.cereshop.app.service.product.CereProductSkuService;
import com.shop.cereshop.app.service.product.CereShopProductService;
import com.shop.cereshop.app.service.seckill.CereShopSeckillService;
import com.shop.cereshop.app.service.shop.CerePlatformShopservice;
import com.shop.cereshop.app.service.shop.CereShopCommentService;
import com.shop.cereshop.app.service.shop.CereShopConversionService;
import com.shop.cereshop.app.service.shop.CereShopVisitService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.constant.ParamEnum;
import com.shop.cereshop.commons.domain.buyer.CereBuyerCommentLike;
import com.shop.cereshop.commons.domain.buyer.CereBuyerSeckillVisit;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.collect.CereBuyerCollect;
import com.shop.cereshop.commons.domain.collect.CereBuyerFootprint;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.distributor.CereShopDistributor;
import com.shop.cereshop.commons.domain.product.CereShopProduct;
import com.shop.cereshop.commons.domain.product.Classify;
import com.shop.cereshop.commons.domain.shop.CereShopConversion;
import com.shop.cereshop.commons.domain.shop.CereShopVisit;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.QRCodeUtil;
import com.shop.cereshop.commons.utils.TimeUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CereShopProductServiceImpl implements CereShopProductService {

    @Value("${exchangeRate}")
    private Integer exchangeRate;
    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.secret}")
    private String secret;

    @Autowired
    private CereShopProductDAO cereShopProductDAO;

    @Autowired
    private CerePlatformActivityService cerePlatformActivityService;

    @Autowired
    private CerePlatformShopservice cerePlatformShopservice;

    @Autowired
    private CereBuyerReceiveService cereBuyerReceiveService;

    @Autowired
    private CereShopCommentService cereShopCommentService;

    @Autowired
    private StringRedisService stringRedisService;

    @Autowired
    private CereShopDistributorService cereShopDistributorService;

    @Autowired
    private CereShopVisitService cereShopVisitService;

    @Autowired
    private CereProductSkuService cereProductSkuService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private CereShopConversionService cereShopConversionService;

    @Autowired
    private CereBuyerCouponService cereBuyerCouponService;

    @Autowired
    private CereCommentWordService cereCommentWordService;

    @Autowired
    private CereBuyerCollectService cereBuyerCollectService;

    @Autowired
    private CereBuyerFootprintService cereBuyerFootprintService;

    @Autowired
    private CereShopGroupWorkService cereShopGroupWorkService;

    @Autowired
    private CereShopSeckillService cereShopSeckillService;

    @Autowired
    private CereShopDiscountService cereShopDiscountService;

    @Autowired
    private CereBuyerCommentLikeService cereBuyerCommentLikeService;

    @Autowired
    private CereShopCouponService cereShopCouponService;

    @Autowired
    private CereBuyerShopCouponService cereBuyerShopCouponService;

    @Autowired
    private CereBuyerSeckillVisitService cereBuyerSeckillVisitService;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 商品详情前缀
     */
    @Value("${goods_url}")
    private String goodsUrl;

    @Value("${goods_ticketUrl}")
    private String goodsTicketUrl;

    @Override
    public CereShopProduct selectByPrimaryKey(Long id) {
        return cereShopProductDAO.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public ProductDetail getById(ProductParam param, CereBuyerUser user) throws Exception {
        CereShopProduct product = cereShopProductDAO.selectByPrimaryKey2(param.getProductId());
        if (product==null){
            throw new CoBusinessException(CoReturnFormat.DELETE_OR_REMOVE);
        }
        ProductDetail detail;
        String time = TimeUtils.yyMMddHHmmss();
        if (user != null) {
            //新增访问记录
            CereShopVisit visit = new CereShopVisit();
            visit.setBuyerUserId(user.getBuyerUserId());
            visit.setShopId(param.getShopId());
            visit.setVisitTime(time);
            visit.setTerminal(param.getTerminal());
            visit.setSystem(param.getSystem());
            visit.setCity(param.getCity());
            cereShopVisitService.insert(visit);
            //新增转化数据
            CereShopConversion cereShopConversion = new CereShopConversion();
            cereShopConversion.setShopId(param.getShopId());
            cereShopConversion.setCreateTime(time);
            cereShopConversion.setType(ParamEnum.CONVERSION_VISIT.getCode());
            cereShopConversionService.insert(cereShopConversion);
            //新增足迹
            CereBuyerFootprint cereBuyerFootprint = new CereBuyerFootprint();
            cereBuyerFootprint.setBuyerUserId(user.getBuyerUserId());
            cereBuyerFootprint.setProductId(param.getProductId());
            cereBuyerFootprint.setCreateTime(time);
            cereBuyerFootprint.setShopId(param.getShopId());
            cereBuyerFootprint.setSkuId(param.getSkuId());
            cereBuyerFootprint.setSelected(IntegerEnum.NO.getCode());
            cereBuyerFootprintService.insert(cereBuyerFootprint);
        }
        //查询商品详情数据
        detail = cereShopProductDAO.findBySkuId(param.getSkuId(), param.getShopId());
        //如果是积分商品则乘以倍率
        if (detail != null) {
            if (detail.getClassifyId().equals(Long.valueOf(7))) {
                detail.setPrice(detail.getPrice().multiply(BigDecimal.valueOf(exchangeRate)));
                detail.setOriginalPrice(detail.getOriginalPrice().multiply(BigDecimal.valueOf(exchangeRate)));
            }
        }
        if (detail != null) {
            if (!EmptyUtils.isEmpty(param.getShopGroupWorkId())) {
                //如果是从活动专区进来
                //查询拼团商品数据
                detail = cereShopGroupWorkService.getById(user, param, detail);
                detail.setShopGroupWorkId(param.getShopGroupWorkId());
                return detail;
            }
            if (!EmptyUtils.isEmpty(param.getShopSeckillId())) {
                //查询秒杀商品数据
                detail = cereShopSeckillService.getById(user, param, detail);
                detail.setShopSeckillId(param.getShopSeckillId());
                if (user != null) {
                    //新增浏览记录
                    CereBuyerSeckillVisit cereBuyerSeckillVisit = new CereBuyerSeckillVisit();
                    cereBuyerSeckillVisit.setBuyerUserId(user.getBuyerUserId());
                    cereBuyerSeckillVisit.setShopSeckillId(param.getShopSeckillId());
                    cereBuyerSeckillVisit.setVisitTime(TimeUtils.yyMMddHHmmss());
                    cereBuyerSeckillVisitService.insert(cereBuyerSeckillVisit);
                }
                return detail;
            }
            if (!EmptyUtils.isEmpty(param.getShopDiscountId())) {
                //查询限时折扣商品数据
                detail = cereShopDiscountService.getById(user, param, detail);
                detail.setShopDiscountId(param.getShopDiscountId());
                return detail;
            }
            //都不满足代表是从商品详情进来,判断该商品是否参与活动
            if (!EmptyUtils.isEmpty(detail.getShopGroupWorkId())) {
                param.setShopGroupWorkId(detail.getShopGroupWorkId());
                //查询拼团商品数据
                detail = cereShopGroupWorkService.getById(user, param, detail);
                detail.setShopGroupWorkId(param.getShopGroupWorkId());
                return detail;
            }
            if (!EmptyUtils.isEmpty(detail.getShopSeckillId())) {
                param.setShopSeckillId(detail.getShopSeckillId());
                //查询秒杀商品数据
                detail = cereShopSeckillService.getById(user, param, detail);
                detail.setShopSeckillId(param.getShopSeckillId());
                if (user != null) {
                    //新增浏览记录
                    CereBuyerSeckillVisit cereBuyerSeckillVisit = new CereBuyerSeckillVisit();
                    cereBuyerSeckillVisit.setBuyerUserId(user.getBuyerUserId());
                    cereBuyerSeckillVisit.setShopSeckillId(param.getShopSeckillId());
                    cereBuyerSeckillVisit.setVisitTime(TimeUtils.yyMMddHHmmss());
                    cereBuyerSeckillVisitService.insert(cereBuyerSeckillVisit);
                }
                return detail;
            }
            if (!EmptyUtils.isEmpty(detail.getShopDiscountId())) {
                param.setShopDiscountId(detail.getShopDiscountId());
                //查询限时折扣商品数据
                detail = cereShopDiscountService.getById(user, param, detail);
                detail.setShopDiscountId(param.getShopDiscountId());
                return detail;
            }
            //查询正常商品数据逻辑
            //查询商品图片
            detail.setImages(cereShopProductDAO.findImages(param.getProductId()));
            //查询最新收货地址数据
            if (user != null) {
                detail.setReceive(cereBuyerReceiveService.findlatelyReceiveByUserId(user.getBuyerUserId()));
                //查询该商品收藏id
                CereBuyerCollect collect = cereBuyerCollectService.findByUserProduct(user.getBuyerUserId(), detail.getProductId());
                if (collect != null) {
                    detail.setCollectId(collect.getCollectId());
                    detail.setIfCollect(collect.getState());
                }
            }
            //查询商品评论信息
            List<BuyerComment> comments = cereShopCommentService.findByProductId(param.getProductId());
            //封装评论图片数组数据
            if (!EmptyUtils.isEmpty(comments)) {
                comments.forEach(buyerComment -> {
                    buyerComment.setImages(EmptyUtils.getImages(buyerComment.getImage()));
                    buyerComment.setAddImages(EmptyUtils.getImages(buyerComment.getAddImage()));
                    buyerComment.setValues(EmptyUtils.getImages(buyerComment.getValue()));
                    //设置是否点赞
                    if (user != null) {
                        CereBuyerCommentLike cereBuyerCommentLike = cereBuyerCommentLikeService.findByUserIdAndCommentId(user.getBuyerUserId(), buyerComment.getCommentId());
                        if (cereBuyerCommentLike != null) {
                            buyerComment.setIfLike(cereBuyerCommentLike.getIfLike());
                        }
                    }
                });
                //查询该商品评论关联关键词统计数据
                List<CommentWord> words = cereCommentWordService.findByProductId(param.getProductId());
                detail.setWords(words);
            }
            Integer size = comments.size();
            detail.setTotal2(size);
            List<BuyerComment> c2 = new ArrayList<>();
            if (size>2){
                c2.add(comments.get(0));
                c2.add(comments.get(1));
            }else {
                c2 = comments;
            }
            detail.setComments(c2);
            //查询店铺商品总类数
            detail.setClassifyNumber(cereShopProductDAO.findClassifyNumber(param.getShopId()).size());
            //定义优惠券拼接信息
            String couponSplicing = "";
            //查询平台优惠券
            List<ProductCoupon> tools;
            if (user != null) {
                //过滤已使用和已过期的优惠券
                tools = cerePlatformActivityService.findCouponByProductIdAndUserId(user.getBuyerUserId(), param.getProductId());
                tools = tools.stream()
                        .filter(productCoupon -> IntegerEnum.COUPON_NOT_HAVE.getCode().equals(productCoupon.getState())
                                || IntegerEnum.COUPON_HAVE.getCode().equals(productCoupon.getState()))
                        .collect(Collectors.toList());
            } else {
                tools = cerePlatformActivityService.findCouponByProductId(param.getProductId());
            }
            detail.setMarkTools(tools);
            //设置活动图片数组
            if (!EmptyUtils.isEmpty(tools)) {
                detail.setCouponImages(tools.stream().map(ProductCoupon::getImage).distinct().collect(Collectors.toList()));
            }
            //然后查询店铺优惠券
            List<ProductCoupon> shopCoupons = null;
            if (user != null) {
                shopCoupons = cereShopCouponService.findByProductIdAndUserId(user.getBuyerUserId(), param.getProductId());
                if (!EmptyUtils.isEmpty(shopCoupons)) {
                    //设置优惠券状态
                    shopCoupons.forEach(shopCoupon -> {
                        if (!EmptyUtils.isEmpty(shopCoupon.getFrequency())) {
                            //如果有限制领取次数
                            if (shopCoupon.getFrequency().equals(shopCoupon.getCount())) {
                                //如果限制领取次数=用户已领取优惠券总数,修改店铺优惠券状态为已领取
                                shopCoupon.setState(IntegerEnum.COUPON_HAVE.getCode());
                            }
                        }
                    });
                }
            } else {
                shopCoupons = cereShopCouponService.findByProductId(param.getProductId());
            }
            detail.setShopMarkTools(shopCoupons);
            if (!EmptyUtils.isEmpty(tools)) {
                //设置优惠券内容
                tools.forEach(tool -> {
                    tool.setContent("满" + tool.getFullMoney().stripTrailingZeros().toPlainString() +
                            "减" + tool.getReduceMoney().stripTrailingZeros().toPlainString() + "元");
                });
                couponSplicing = tools.stream().map(tool -> "满" + tool.getFullMoney().stripTrailingZeros().toPlainString()
                        + "减" + tool.getReduceMoney().stripTrailingZeros().toPlainString()).collect(Collectors.joining(";"));
            }
            if (!EmptyUtils.isEmpty(shopCoupons)) {
                shopCoupons.forEach(tool -> {
                    if (IntegerEnum.COUPON_TYPE_REDUTION.getCode().equals(tool.getCouponType())) {
                        tool.setContent("满" + tool.getFullMoney().stripTrailingZeros().toPlainString() +
                                "减" + tool.getReduceMoney().stripTrailingZeros().toPlainString() + "元");
                    } else {
                        tool.setContent(tool.getReduceMoney().stripTrailingZeros().toPlainString() + "折券");
                    }
                });
                couponSplicing += shopCoupons.stream().map(tool ->
                        IntegerEnum.COUPON_TYPE_REDUTION.getCode().equals(tool.getCouponType()) ?
                                "满" + tool.getFullMoney().stripTrailingZeros().toPlainString()
                                        + "减" + tool.getReduceMoney().stripTrailingZeros().toPlainString() :
                                tool.getReduceMoney().stripTrailingZeros().toPlainString() + "折券").collect(Collectors.joining(";"));
            }
            detail.setCouponSplicing(couponSplicing);
            //查询同类商品
            List<Product> similarProducts = cereShopProductDAO.findSimilarProducts(detail.getClassifyId());
            detail.setSimilarProducts(similarProducts);
        }
        return detail;
    }
    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public PageInfo<?> talk(ProductParam param, CereBuyerUser user, Integer page,
                            Integer row) {
//        List<BuyerComment> count = cereShopCommentService.findByProductId(param.getProductId());
        PageHelper.startPage(page, row);
        //查询商品评论信息
        List<BuyerComment> comments = cereShopCommentService.findByProductId(param.getProductId());
        //封装评论图片数组数据
        if (!EmptyUtils.isEmpty(comments)) {
            for (BuyerComment buyerComment : comments) {
                buyerComment.setImages(EmptyUtils.getImages(buyerComment.getImage()));
                buyerComment.setAddImages(EmptyUtils.getImages(buyerComment.getAddImage()));
                buyerComment.setValues(EmptyUtils.getImages(buyerComment.getValue()));
                //设置是否点赞
                if (user != null) {
                    CereBuyerCommentLike cereBuyerCommentLike = cereBuyerCommentLikeService.findByUserIdAndCommentId(user.getBuyerUserId(), buyerComment.getCommentId());
                    if (cereBuyerCommentLike != null) {
                        buyerComment.setIfLike(cereBuyerCommentLike.getIfLike());
                    }
                }
            }
        }
        PageInfo<BuyerComment> buyerCommentPageInfo = new PageInfo<>(comments);
//        buyerCommentPageInfo.setTotal(count.size());
        return buyerCommentPageInfo;
    }
    @Override
    public ProductSkus getProducts(SkuParam param) throws CoBusinessException, Exception {
        //查询该商品所有规格名
        List<SkuName> names = cereProductSkuService.findSkuNames(param.getProductId());
        if (!EmptyUtils.isEmpty(names)) {
            if (!EmptyUtils.isEmpty(names.get(0).getSkuName())) {
                //多款式
                names.forEach(name -> name.setValues(cereProductSkuService.findSkuValues(name.getSkuName(), param.getProductId())));
            } else {
                //单款式
                names.get(0).setValues(cereProductSkuService.findOneValues(param.getSkuId()));
            }
        }
        //查询当前商品第一条规格数据
        ProductSkus productSkus = null;
        if (!EmptyUtils.isEmpty(param.getSkuId())) {
            productSkus = cereProductSkuService.findSku(param.getSkuId());
        } else {
            productSkus = cereProductSkuService.findFirstSku(param.getProductId());
        }
        if (productSkus != null) {
            productSkus.setNames(names);
            //查询活动数据
            SkuTool skuTool = cereProductSkuService.findTool(param.getProductId());
            if (skuTool != null) {
                if (IntegerEnum.COUPON_STATE_START.getCode().equals(skuTool.getState())) {
                    skuTool.setIfEnable(IntegerEnum.NO.getCode());
                } else {
                    if (IntegerEnum.ENABLE_START.getCode().equals(skuTool.getIfEnable())
                            && !EmptyUtils.isEmpty(skuTool.getEnableTime())) {
                        //如果开启活动预热,计算预热几小时前的时间
                        String enableTime = TimeUtils.headDate(skuTool.getStartTime(), skuTool.getEnableTime());
                        //判断当前时间是否处于预热时间和活动开始时间之间
                        if (TimeUtils.isBelong(enableTime, skuTool.getStartTime())) {
                            //如果处于,需要展示预热信息
                            skuTool.setIfEnable(IntegerEnum.YES.getCode());
                        }
                    }
                }
                productSkus.setSkuTool(skuTool);
            }
        }
        //查询该商品所有组合规格数据封装到map
        List<Sku> skus = cereProductSkuService.findSkuByProductId(param.getProductId());
        if (!EmptyUtils.isEmpty(skus)) {
            Map<String, Sku> map = new HashMap<>();
            ProductSkus finalProductSkus = productSkus;
            //定义是否活动数据
            boolean flag = false;
            skus.forEach(sku -> {

                if (EmptyUtils.isEmpty(sku.getImage())) {
                    sku.setImage(finalProductSkus.getImage());
                }
                //查询规格所有规格值拼接字符串
                String key = cereProductSkuService.findValueBySkuId(sku.getSkuId());
                if (EmptyUtils.isEmpty(key)) {
                    key = "单款项";
                }
                map.put(key, sku);
            });
            productSkus.setMap(map);
        }
        return productSkus;
    }

    @Override
    public List<Product> getSearchProducts(SearchParam param) throws CoBusinessException {
        return cereShopProductDAO.getSearchProducts(param);
    }

    @Override
    public ShareProduct share(ShareParam shareParam, CereBuyerUser user) throws CoBusinessException, Exception {
        //查询商品数据
        ShareProduct shareProduct = cereShopProductDAO.findShareProduct(shareParam.getSkuId());
        if (shareProduct != null) {
            shareProduct.setName(user.getWechatName());
            shareProduct.setHeadImage(user.getHeadImage());
            //生成小程序码
//            RestTemplate rest = new RestTemplate();
//            InputStream inputStream = null;
//            AppletTokenResult appletTokenResult = QRCodeUtil.getAppletToken("");
//            if(appletTokenResult == null || StringUtil.isEmpty(appletTokenResult.getAccess_token())){
////                throw new CommonException("小程序token获取失败！");
//            }
//            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
//                    +appletTokenResult.getAccess_token();
//            Map<String, Object> param= new HashMap<String, Object>();
//            String urlString = URLEncoder.encode("=", "GBK");
//            //查询分销员邀请码
//            String invitationCode = cereShopDistributorService.findInvitationCode(shareParam.getDistributorId());
//            param.put("scene", shareParam.getShopId()+"-"+
//                    shareParam.getDistributorId()+"-"+invitationCode);
//            param.put("page", "https://shopapi.zkthink.com/#/pages/goodsModule/goodsDetails?id='"+shareProduct.getProductId()
//                    +"'&salesId='"+shareParam.getDistributorId()+"'");
//            param.put("width", 430);
//            param.put("auto_color", false);
//            Map<String,Object> line_color = new HashMap<>();
//            line_color.put("r", 0);
//            line_color.put("g", 0);
//            line_color.put("b", 0);
//            param.put("line_color", line_color);
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON);
//            HttpEntity<String> requestEntity = new HttpEntity<String>(new Gson().toJson(param), headers);
//            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST,
//                    requestEntity, byte[].class, new Object[0]);
//            byte[] result = entity.getBody();
//            inputStream = new ByteArrayInputStream(result);
//            byte[] bytes = QRCodeUtil.toByteArray(inputStream);
//            String qrcode = uploadService.uploadByte("商品分享", bytes);
//            shareProduct.setShareImage(qrcode);
        }
        return shareProduct;
    }

    @Override
    public Page getCanvasProducts(CanvasAppProductParam param) throws CoBusinessException, Exception {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<CanvasProduct> list;
        if (IntegerEnum.CANVAS_ACTIVITY_GROUP_WORK.getCode().equals(param.getType())) {
            list = cereShopProductDAO.getGroupWorkProducts(param);
        } else if (IntegerEnum.CANVAS_ACTIVITY_SECKILL.getCode().equals(param.getType())) {
            list = cereShopProductDAO.getSeckillProducts(param);
        } else if (IntegerEnum.CANVAS_ACTIVITY_DISCOUNT.getCode().equals(param.getType())) {
            list = cereShopProductDAO.getDiscountProducts(param);
        } else {
            list = cereShopProductDAO.getCanvasProducts(param);
        }
        if (!EmptyUtils.isEmpty(list)) {
            for (CanvasProduct product : list) {
                if (IntegerEnum.COUPON_STATE_START.getCode().equals(product.getState())) {
                    //活动进行中
                    product.setIfEnable(IntegerEnum.NO.getCode());
                    //设置秒杀活动倒计时
                    product.setTime(TimeUtils.getCountDownByTime(TimeUtils.yyMMddHHmmss(), product.getEndTime()));
                } else if (IntegerEnum.COUPON_STATE_READY.getCode().equals(product.getState())) {
                    if (IntegerEnum.ENABLE_START.getCode().equals(product.getIfEnable())
                            && !EmptyUtils.isEmpty(product.getEnableTime())) {
                        //如果开启活动预热,计算预热几小时前的时间
                        String enableTime = TimeUtils.headDate(product.getStartTime(), product.getEnableTime());
                        //判断当前时间是否处于预热时间和活动开始时间之间
                        if (TimeUtils.isBelong(enableTime, product.getStartTime())) {
                            //如果处于,需要展示预热信息
                            product.setIfEnable(IntegerEnum.YES.getCode());
                        }
                    }
                }
            }
        }
        PageInfo<CanvasProduct> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    public List<Classify> getClassify() throws CoBusinessException {
        //查询所有一级类目
        List<Classify> list = cereShopProductDAO.findAllClassify();
        //查询所有子节点类目
        List<Classify> childs = cereShopProductDAO.findChildsClassify();
        if (!EmptyUtils.isEmpty(list)) {
            Map<String, Integer> map = new HashMap<>();
            list.forEach((classify -> {
                setChildsIndex(classify, childs, map);
            }));
        }
        return list;
    }

    @Override
    public CereShopDistributor check(Long shopId, CereBuyerUser user) throws CoBusinessException {
        return cereShopDistributorService.check(shopId, user.getBuyerUserId());
    }

    @Override
    public void deleteAllSearch(CereBuyerUser user) throws CoBusinessException {
        if (user != null) {
            cereShopProductDAO.deleteAllSearch(user.getBuyerUserId());
        }
    }

    @Override
    public List<String> findImages(Long productId) {
        return cereShopProductDAO.findImages(productId);
    }

    @Override
    public List<String> findSkuImages(Long productId) {
        return cereShopProductDAO.findSkuImages(productId);
    }

    @Override
    public List<Product> findSimilarProducts(Long classifyId) {
        return cereShopProductDAO.findSimilarProducts(classifyId);
    }

    @Override
    public List<Long> findClassifyNumber(Long shopId) {
        return cereShopProductDAO.findClassifyNumber(shopId);
    }

    @Override
    public Integer findPayNumber(Long skuId) {
        return cereShopProductDAO.findPayNumber(skuId);
    }

    @Override
    public String getSharePic(ProductParam param, CereBuyerUser user) throws CoBusinessException {
        if (user == null) {
            throw new CoBusinessException(CoReturnFormat.USER_NOT_LOGIN);
        }
        try {
            ProductDetail detail = getById(param, user);
            int env = param.getTerminal();
//            String itemPicUrl = CollectionUtils.isNotEmpty(detail.getImages()) ? detail.getImages().get(0) : "";
            String shareHeadUrl = user.getHeadImage();
            String shareName = user.getName();
            if (StringUtils.isBlank(shareName)) {
                shareName = user.getWechatName();
            }
            String itemName = detail.getProductName();
            BigDecimal itemPrice = detail.getPrice();
            CereShopProduct cereShopProduct = cereShopProductDAO.selectByPrimaryKey(param.getProductId());
            String itemPicUrl = cereShopProduct.getShareImage();
            if (cereShopProduct.getProductNo() == null || "".equals(cereShopProduct.getProductNo())) {
                cereShopProduct.setProductNo("0");
            }

            String itemUrlSuffix = "?shopId=" + param.getShopId() + "&productId=" + param.getProductId() + "&skuId=" + param.getSkuId()
                    + "&productNo=" + cereShopProduct.getProductNo()
                    + "&buyerUserId=" + user.getBuyerUserId();
//            //获取缓存中的token
//            String accessToken = (String) stringRedisService.get(appId + secret + "accessToken");
//            Map map = null;
//            //没有在查询
//            if("".equals(accessToken)){
//                try {
//                    map = WeixinUtil.getAccessToken(appId, secret);
//                    stringRedisService.set(appId + secret + "accessToken",accessToken, Long.parseLong(map.get("expires_in").toString())*1000);
//                    accessToken = (String) map.get("access_token");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            String accessToken = WeixinUtil.getAccessToken(appId, secret);
            return genPoster(cereShopProduct.getProductNo(), param,env, itemPicUrl, shareHeadUrl, shareName, itemName, itemPrice, itemUrlSuffix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer getsheStateByid(Long productId) {
        return cereShopProductDAO.getsheStateByid(productId);
    }

    private Classify setChildsIndex(Classify parent, List<Classify> all, Map<String, Integer> map) throws ArrayIndexOutOfBoundsException {
        if (!parent.getParentId().equals(0L)) {
            //回调进来的,设置回调执行次数+1
            map.put("callback", map.get("callback") + 1);
        } else {
            //如果是根节点进来,初始化回调执行次数
            map.put("callback", 0);
        }
        List<Classify> childs = new ArrayList<>();
        if (!EmptyUtils.isEmpty(all)) {
            for (int i = 0; i < all.size(); i++) {
                if (all.size() > 0) {
                    if (i < 0) {
                        i = 0;
                    }
                    Classify classify = all.get(i);
                    //设置按钮菜单权限
                    if (parent.getId().equals(classify.getParentId())) {
                        all.remove(i);
                        i--;
                        //执行回调
                        Classify itemPermission = setChildsIndex(classify, all, map);
                        childs.add(itemPermission);
                        //判断当前是否回到最高级菜单节点
                        if (parent.getParentId().equals(0L)) {
                            //如果是,计算索引值=当前索引值-（回调执行次数-1）
                            i = i - (map.get("callback") - 1);
                            //初始化回调执行次数
                            map.put("callback", 0);
                        }
                    }
                }
            }
            parent.setChilds(childs);
        }
        return parent;
    }

    /**
     * 生成分享海报
     *
     * @param env           1-APP 2-小程序 3-H5
     * @param itemPicUrl
     * @param shareHeadUrl
     * @param shareName
     * @param itemName
     * @param itemPrice
     */
    private String genPoster(String productNo, ProductParam param,int env, String itemPicUrl, String shareHeadUrl,
                             String shareName, String itemName, BigDecimal itemPrice,
                             String itemUrlSuffix) throws Exception {

        //底图
//        String ditu = "https://dl-fuzhou-shop.oss-cn-shanghai.aliyuncs.com/test/2021-07-22/9f96c299738b4117bb6dda5739bdd875%E7%BB%84%20322%403x.png";
        String ditu = "https://dl-fuzhou-shop.oss-cn-shanghai.aliyuncs.com/test/2021-07-23/5a192e0596ac4e93975dbafc3d5f213c.png";
        int width = 320;
        int height = 500;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);


        Graphics2D g2d = image.createGraphics();

        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.OPAQUE);
        g2d.dispose();
        g2d = image.createGraphics();

        final Font logoFont = new Font("SimSun", Font.PLAIN, 25);

        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, width, height);

        g2d.setColor(new Color(182, 249, 225));
//        g2d.setStroke(new BasicStroke(0));
        g2d.setStroke(new BasicStroke(1));

        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        BufferedImage proImgA = ImageIO.read(new URL(ditu));
        g2d.drawImage(proImgA.getScaledInstance(320, 500, Image.SCALE_SMOOTH), 0, 0, null);
        BufferedImage proImg = ImageIO.read(new URL(itemPicUrl));
        //1比1比例图片,
        g2d.drawImage(proImg.getScaledInstance(320, 325, Image.SCALE_SMOOTH), (width-320)/2, 0, null);
        //2比1比例图片 ,取中间
//        g2d.drawImage(proImg.getScaledInstance(640, 325, Image.SCALE_DEFAULT), -160, 0, null);


//        BufferedImage shareHeadImg = ImageIO.read(new URL(shareHeadUrl));
//        g2d.drawImage(shareHeadImg.getScaledInstance(40, 40, Image.SCALE_SMOOTH),20, 360, null);


        //名字超出长度省略
        if(shareName.length() > 6){
            shareName = shareName.substring(0, 5) + "...";
        }
        //xxx分享了一个商品
        g2d.setPaint(Color.BLACK);
//        g2d.setFont(new Font("Alibaba PuHuiTi R", Font.PLAIN, 18));
        g2d.setFont(new Font("SimSun",0, 18));
        FontMetrics fm = g2d.getFontMetrics(g2d.getFont());
        int textWidth = fm.stringWidth(shareName + "分享了一个商品");
//        g2d.drawString(shareName, 75, 385);

//        if(itemName.length() > 12){
//            itemName = itemName.substring(0, 12) + "...";
//        }
        //商品名称
        g2d.setPaint(Color.BLACK);
//        g2d.setFont(logoFont);
//        g2d.setFont(new Font("SimSun",Font.PLAIN, 16));
        g2d.setFont(new Font("OPPOSans",Font.BOLD, 16));
        FontMetrics fm2 = g2d.getFontMetrics(g2d.getFont());
        int textWidth2 = fm2.stringWidth(itemName);
        if (itemName.length()>15 && itemName.length()<=41){
            String i1 = itemName.substring(0, 15);
            String i2 = itemName.substring(15);
            g2d.drawString(i1,82, 360);
            g2d.drawString(i2,5, 380);
        }else if (itemName.length()<=16){
            g2d.drawString(itemName,82, 360);
        }else if (itemName.length()>41){
            String i1 = itemName.substring(0, 15);
            String i2 = itemName.substring(15,40)+"...";
            g2d.drawString(i1,82, 360);
            g2d.drawString(i2,5, 380);
        }

        //填写售价
        g2d.setPaint(Color.RED);
//        g2d.setFont(new Font("Alibaba PuHuiTi R", Font.BOLD, 30));
//        g2d.setFont(new Font("SimSun", Font.BOLD, 16));
        g2d.setFont(new Font("OPPOSans", Font.BOLD, 16));
        FontMetrics fm3 = g2d.getFontMetrics(g2d.getFont());
        if (param.getClassifyId()!=7){
//            int textWidth3 = fm3.stringWidth("￥" + itemPrice.toStringing());
            int textWidth3 = fm3.stringWidth(itemPrice.toString());
            g2d.drawString("￥"+itemPrice, 60, 415);
        }
//        else {
////            525
//            int textWidth3 = fm3.stringWidth(itemPrice.toString()+"积分");
//            g2d.drawString( itemPrice +"积分", (width - textWidth3) / 2, 360);
//        }


        //画分割线
//        g2d.setPaint(new Color(194, 194, 194));
//        g2d.drawLine(10, 385, 310, 385);

        //生成底部文案 和 二维码
        g2d.setFont(new Font("SimSun", Font.PLAIN, 17));
        BufferedImage qrCode = null;
        if (env == 1 || env == 2) {
            g2d.drawString("长按识别小程序", 15, 413);
//            qrCode = WechatUtil.getWxacode(accessToken, goodsUrl + itemUrlSuffix);
        } else {
//            g2d.drawString("长按识别二维码购买商品", 15, 413);
            if("0".equals(productNo)){
                qrCode = QRCodeUtil.createImage(goodsUrl + itemUrlSuffix, null, true);
            }else{
                qrCode = QRCodeUtil.createImage(goodsTicketUrl + itemUrlSuffix, null, true);
            }
        }
        //画出图片
        if (qrCode != null) {
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
            g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
            g2d.drawImage(qrCode.getScaledInstance(60, 60, Image.SCALE_SMOOTH),
                    250, 412, null);
        }
        //画圆
//        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
//        Ellipse2D.Double shape = new Ellipse2D.Double(20, 360, 45, 45);
//        g2d.setClip(shape);
//        g2d.drawImage(shareHeadImg.getScaledInstance(45, 45, Image.SCALE_SMOOTH),
//                20, 358, null);
//        g2d.drawImage(shareHeadImg.getScaledInstance(70, 70, Image.SCALE_AREA_AVERAGING), 130, 175, null);


        g2d.dispose();

        String fileName = UUID.randomUUID() + ".png";
        InputStream inputStream = bufferedImageToInputStream(image, fileName);
        return fileUploadService.uploadFile(fileName, inputStream, inputStream.available());
//        读取本地图片
//        return IP + "/images/" + fileName + "";
    }


    /**
     * 将BufferedImage转换为InputStream
     *
     * @param image
     * @return
     */
    public InputStream bufferedImageToInputStream(BufferedImage image, String fileName) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
//            boolean png = ImageIO.write(image, "png", new File( img + fileName + ""));
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
